package org.example.controller;

import org.apache.solr.client.solrj.SolrQuery;
import org.example.entity.NewsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.*;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author GuoChunbo
 * @create 2021-03-15 11:31
 * @Description: 类的描述
 */
@Controller
public class SolrController {

    @Autowired
    SolrTemplate solrTemplate;

    @RequestMapping("list")
    public String list(@RequestParam(defaultValue = "0", required = false) Integer pageno,
                       @RequestParam(defaultValue = "*", required = false) String title,
                       Model model) {
        HighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("title:" + title));
//        SimpleQuery query = new SimpleQuery("title:"+title);
        //分页
        query.setOffset(PageRequest.of(pageno, 10).getOffset());
        query.setRows(10);
        //排序
        query.addSort(Sort.by(new Sort.Order(Sort.Direction.DESC, "createDate")));
        //高亮
        HighlightOptions highlightOptions = new HighlightOptions();
        highlightOptions.addField("title");
        highlightOptions.setSimplePrefix("<strong>");
        highlightOptions.setSimplePostfix("</strong>");
        query.setHighlightOptions(highlightOptions);

        HighlightPage<NewsEntity> newsEntityPage = solrTemplate.
            queryForHighlightPage("news_core", query, NewsEntity.class);
        for (HighlightEntry<NewsEntity> newsEntityHighlightEntry : newsEntityPage.getHighlighted()) {
            if(newsEntityHighlightEntry.getHighlights().size()>0){
                //设置高亮字段的值
                String hlTitle = newsEntityHighlightEntry.getHighlights().get(0).getSnipplets().get(0);
                newsEntityHighlightEntry.getEntity().setTitle(hlTitle);
            }
        }
        model.addAttribute("newsEntityPage", newsEntityPage);
        model.addAttribute("title", title);
        return "index";
    }
}
